import re
import time

from sam import import_csv_path
from sam.util.dbUtil import mysql_env_config_dict, DB
from sam.util.fileUtil2 import read_file
from sam.util.httpUtil import get_web_driver
from sam.util.notifyUtil import work_we_chart_notify
from sam.util.strUtil import filter_symbol_4_word


class NetMusic(object):
    def __init__(self):
        super().__init__()
        self.db = DB(mysql_env_config_dict.get("net"), level="debug")
        self.browser = get_web_driver(headless=False, images_less=False)
        self.id_re = re.compile(r"id=(\d+)?")

    def __del__(self):
        if self.browser:
            self.browser.quit()
            print("无图浏览器退出")

    def fetch_song_url(self, keyword):
        search_url = f"https://music.163.com/#/search/m/?id=1840459406&uct=lTFtRahJVn4haomllHuhzA%3D%3D&app_version=8.2.55&s={keyword}&type=1"
        self.browser.get(url=search_url)
        time.sleep(5)
        self.browser.switch_to.frame("contentFrame")
        if keyword == "伤不起":
            a_element = self.browser.find_element_by_css_selector(
                "div.srchsongst > div:nth-child(3) div.w0 div.text > a")
        else:
            a_element = self.browser.find_element_by_css_selector(
                "div.srchsongst > div:nth-child(1) div.w0 div.text > a")
        song_url = a_element.get_attribute("href")
        id_str = re.search(self.id_re, song_url).group(1)
        self.browser.get(song_url)
        time.sleep(5)
        self.browser.switch_to.frame("contentFrame")
        extend_more_element = self.browser.find_element_by_css_selector("a#flag_ctrl")
        self.browser.execute_script("arguments[0].click();", extend_more_element)
        return id_str

    def extract_song_singer(self):
        singer_str = self.browser.find_element_by_css_selector(
            "div.m-lycifo     div.cnt > p:nth-child(2) > span > a").text.strip()
        return singer_str

    def extract_song_lyric(self):
        lyric_content_str = self.browser.find_element_by_css_selector("#lyric-content").text.strip()
        flag_more_str = self.browser.find_element_by_css_selector("#flag_more").text.strip()
        lyric_str = lyric_content_str + flag_more_str
        lyric_str = filter_symbol_4_word(lyric_str, is_need_filter_start_end=True)
        # lyric_str = re.sub(lyric_none_re, "", lyric_str)
        # lyric_str = filter_symbol_4_word(lyric_str, is_need_filter_start_end=True)
        # lyric_str = lyric_str.replace("\n", " ")
        return lyric_str

    def extract_song_comment(self):
        can_extract_flag = False
        wonderful_cmt_text_list = []
        cmt_element_list = self.browser.find_elements_by_css_selector("div.cmmts > *")
        for cmt_element in cmt_element_list:
            tag_name = cmt_element.tag_name
            if tag_name == "h3":
                if can_extract_flag:
                    break
                else:
                    can_extract_flag = True
                continue
            elif tag_name == "div" and can_extract_flag:
                cmt_user_text = cmt_element.find_element_by_css_selector("div.cntwrap   div.cnt  a").text.strip()
                cmt_content_text = cmt_element.find_element_by_css_selector("div.cntwrap   div.cnt").text.strip()
                new_cmt_content_text = cmt_content_text.replace(cmt_user_text, "")
                word = filter_symbol_4_word(new_cmt_content_text, is_need_filter_start_end=True)
                word = word.replace("\n", " ")
                wonderful_cmt_text_list.append(word)
            else:
                pass
        return ' '.join(wonderful_cmt_text_list)

    def search(self, keyword):
        id_str = self.fetch_song_url(keyword)
        singer_str = self.extract_song_singer()
        lyric_str = self.extract_song_lyric()
        comment_str = self.extract_song_comment()
        item = {
            "sid": id_str
            , "keyword": keyword
            , "singer": singer_str
            , "lyric": lyric_str
            , "comment": comment_str
        }
        print(item)
        self.db.batch_update_by_item_list(
            item_list=[item]
            , table_name="net_music"
            , optional="InsertOrUpdate"
            # , optional="BatchUpdate"
            , batch_size=1
            # , condition={"in": "uuid"}
        )
        print(f"完成关键词 {keyword}")

    def main(self):
        line_list = read_file(import_csv_path)
        for line in line_list:
            keyword = line[0].strip()
            if keyword:
                time.sleep(10)
                print(f"将要抓取  关键词： {keyword}")
                self.search(keyword)
        else:
            print("全部已抓取完毕")
            work_we_chart_notify(f" 当前 批次的 关键词 爬取完了, {line_list[0][0]} -- {line_list[-1][0]}")

    def main2(self):
        keyword_list = [
            "野狼disco"
            , "星辰大海"
            , "倍儿爽"
            , "伤不起"
        ]
        for keyword in keyword_list:
            time.sleep(10)
            print(f"将要抓取  关键词： {keyword}")
            self.search(keyword)
        else:
            print("全部已抓取完毕")


def net_music():
    process = NetMusic()
    process.main2()


def re_test():
    lyric_str = "作词 : 梦然\n作曲 : 梦然\n原唱:梦然\n音乐总监:陈伟伦\n乐队总监/键盘:张继旗\n声乐指导/音乐统筹:王艺轩\n键盘:韩天赫\n吉他:刘桐 毕赫宸\n贝斯:赵浩成\n鼓:王斌\n打击乐: 胡瑀轩\nPGM:张中豪\n和音:王艺轩 曾喃 温勇 付垚 @悦伴歌声\n录音/混音:S.A.G\n\nwao ouououu asxn s  zcoacassbb "
    lyric_str = filter_symbol_4_word(lyric_str, is_need_filter_start_end=True)
    n_ = lyric_str.split("\n\n")[1]
    print(lyric_str)
    print(n_)


if __name__ == "__main__":
    net_music()
